"""
生成测试实验数据脚本
删除所有现有实验，然后生成新的实验数据用于展示各种图表
"""
import random
import math
from datetime import datetime, timedelta
from param_management_client import ParameterClient

def generate_experiments():
    """生成测试实验数据"""
    
    # 连接到项目
    client = ParameterClient(host="localhost", port=8000, project_name="oil3")
    
    print("=" * 60)
    print("实验数据生成脚本")
    print("=" * 60)
    
    # 1. 获取所有现有实验并删除
    print("\n[1/4] 获取现有实验列表...")
    try:
        experiments = client._make_request('GET', f'/projects/oil3/experiments')
        print(f"找到 {len(experiments)} 个现有实验")
        
        if experiments:
            print("\n[2/4] 删除现有实验...")
            for exp in experiments:
                exp_id = exp['id']
                try:
                    client._make_request('DELETE', f'/projects/oil3/experiments/{exp_id}')
                    print(f"  ✓ 已删除实验: {exp['name']} (ID: {exp_id})")
                except Exception as e:
                    print(f"  ✗ 删除实验 {exp_id} 失败: {e}")
        else:
            print("  没有现有实验需要删除")
    except Exception as e:
        print(f"  获取实验列表失败: {e}")
        return
    
    # 2. 生成新的实验数据
    print("\n[3/4] 生成新的实验数据...")
    
    # 生成多个实验，每个实验有不同的时间戳和数据类型
    experiments_to_create = [
        {
            "name": "产量趋势分析",
            "description": "展示产量随时间的变化趋势",
            "data_types": ["time_series", "scalar"],
            "categories": ["产量指标", "效率指标"]
        },
        {
            "name": "成本对比分析",
            "description": "不同方案的成本对比",
            "data_types": ["scalar", "comparison"],
            "categories": ["成本指标", "投资指标"]
        },
        {
            "name": "多维度性能评估",
            "description": "综合性能的多维度评估",
            "data_types": ["radar", "scalar", "time_series"],
            "categories": ["性能指标", "质量指标", "环境指标"]
        },
        {
            "name": "年度数据汇总",
            "description": "年度各项指标的汇总数据",
            "data_types": ["scalar", "bar"],
            "categories": ["年度汇总", "月度对比"]
        },
        {
            "name": "预测模型结果",
            "description": "基于历史数据的预测结果",
            "data_types": ["time_series", "forecast"],
            "categories": ["预测结果", "历史数据"]
        },
        {
            "name": "优化方案对比",
            "description": "不同优化方案的对比分析",
            "data_types": ["comparison", "scalar"],
            "categories": ["方案A", "方案B", "方案C"]
        },
        {
            "name": "实时监控数据",
            "description": "实时采集的监控数据",
            "data_types": ["time_series", "scalar"],
            "categories": ["实时指标", "告警信息"]
        },
        {
            "name": "综合评估报告",
            "description": "综合评估的各项指标",
            "data_types": ["radar", "scalar", "bar"],
            "categories": ["技术指标", "经济指标", "环境指标"]
        }
    ]
    
    # 为每个实验生成数据
    for i, exp_config in enumerate(experiments_to_create):
        print(f"\n  创建实验: {exp_config['name']}")
        
        # 创建实验收集器（使用不同的时间戳）
        base_time = datetime.now() - timedelta(days=len(experiments_to_create) - i)
        experiment = client.new_experiment(
            name=exp_config['name'],
            description=exp_config['description']
        )
        
        # 根据实验配置生成不同类型的数据
        for category in exp_config['categories']:
            experiment.create_category(category, description=f"{category}相关数据")
            
            # 生成单值数据（用于柱状图、饼图等）
            if "scalar" in exp_config['data_types'] or "bar" in exp_config['data_types']:
                num_scalars = random.randint(3, 6)
                for j in range(num_scalars):
                    metric_name = f"指标{j+1}"
                    value = random.uniform(10, 1000)
                    unit = random.choice(["万元", "吨", "MWh", "%", "次"])
                    experiment.add_scalar(
                        category=category,
                        name=metric_name,
                        value=round(value, 2),
                        unit=unit,
                        description=f"{metric_name}的数值"
                    )
            
            # 生成时间序列数据（用于折线图、面积图等）
            if "time_series" in exp_config['data_types'] or "forecast" in exp_config['data_types']:
                num_series = random.randint(2, 4)
                # 确保同一分类下的所有序列使用相同的长度和索引
                data_length = random.randint(12, 24)
                # 生成统一的索引（可以是月份、年份等）
                if data_length <= 12:
                    index = [f"{i+1}月" for i in range(data_length)]
                elif data_length <= 24:
                    index = [f"{i+1}月" if i < 12 else f"{i-11}月" for i in range(data_length)]
                else:
                    index = [f"第{i+1}期" for i in range(data_length)]
                
                for j in range(num_series):
                    series_name = f"趋势{j+1}"
                    base_value = random.uniform(50, 500)
                    
                    # 根据实验类型生成不同的趋势
                    if "预测" in exp_config['name']:
                        # 预测数据：平滑增长
                        values = [base_value * (1 + 0.05 * i + random.uniform(-0.02, 0.02)) 
                                 for i in range(data_length)]
                    elif "趋势" in exp_config['name']:
                        # 趋势数据：可能有波动
                        values = [base_value * (1 + 0.1 * math.sin(i * 0.5) + random.uniform(-0.1, 0.1)) 
                                 for i in range(data_length)]
                    else:
                        # 其他：随机波动
                        values = [base_value * (1 + random.uniform(-0.2, 0.2)) 
                                 for i in range(data_length)]
                    
                    experiment.add_series(
                        category=category,
                        name=series_name,
                        values=[round(v, 2) for v in values],
                        index=index,  # 使用统一的索引
                        unit=random.choice(["万元", "吨", "MWh", "%"]),
                        description=f"{series_name}的时间序列数据"
                    )
            
            # 生成雷达图数据（多个指标的多维度对比）
            if "radar" in exp_config['data_types']:
                radar_metrics = ["技术指标", "经济指标", "环境指标", "社会指标", "管理指标"]
                for metric in radar_metrics[:random.randint(4, 5)]:
                    value = random.uniform(60, 100)  # 雷达图通常用0-100的分数
                    experiment.add_scalar(
                        category=category,
                        name=metric,
                        value=round(value, 1),
                        unit="分",
                        description=f"{metric}的评分"
                    )
        
        # 上传实验数据
        try:
            experiment.upload()
            print(f"    ✓ 实验数据已上传: {exp_config['name']}")
        except Exception as e:
            print(f"    ✗ 上传失败: {e}")
    
    # 3. 验证结果
    print("\n[4/4] 验证实验结果...")
    try:
        experiments = client._make_request('GET', f'/projects/oil3/experiments')
        print(f"  成功创建 {len(experiments)} 个实验")
        for exp in experiments:
            print(f"    - {exp['name']} (ID: {exp['id']}, 创建时间: {exp['created_at']})")
    except Exception as e:
        print(f"  验证失败: {e}")
    
    print("\n" + "=" * 60)
    print("实验数据生成完成！")
    print("=" * 60)

if __name__ == "__main__":
    generate_experiments()

